package com.tong.embeddedvr.filter;

import com.tong.embeddedvr.dto.UserOutputDTO;
import com.tong.embeddedvr.entity.UserEntity;
import com.tong.embeddedvr.utils.CommonUtil;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns = "/user/*",filterName = "userFilter")
public class UserFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(UserFilter.class);

    private final String EXCLUDED_URL[] = {"/login","/register","/test","/sendRegisterMsg","/sendLoginMsg","/logout"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 这里的过滤器暂时只用来添加头,后面会拿来拦截
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //允许对应的源
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        //允许携带cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //对session放行
        response.setHeader("Set-Cookie","HttpOnly;Secure;SameSite=None");
        //获得url
        String url = ((HttpServletRequest) servletRequest).getServletPath();
        boolean flag = false;
        //确定是否在被排除的URL中
        for (String s : EXCLUDED_URL) {
            if(url.contains(s)){
                flag = true;
            }
        }
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        logger.info("session:[{}]",session.getId());
        UserOutputDTO user = (UserOutputDTO) session.getAttribute("user");
        System.out.println("user:"+user);
        if(flag||user!=null){
            if(user!=null){
                logger.info("用户信息:[{}]",user);
            }
            //取session的前10位作为日志的标记
            ThreadContext.put("logId",session.getId().substring(0,10));
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            servletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter writer = servletResponse.getWriter();
            writer.print(CommonUtil.ajaxReturn(400,"无此权限"));
        }
    }

    @Override
    public void destroy() {

    }
}
